import React from 'react';
import { Image, FlatList, Animated, ActivityIndicator, ScrollView, StyleSheet, Text, View, TouchableOpacity, DeviceEventEmitter, TextInput } from 'react-native';
import { AlertDialog, SimpleItemsBottom } from 'react-native-pickers'

const AnimatedFlatList = Animated.createAnimatedComponent(FlatList);

import ScreenUtils from '../Utils/ScreenUtils'
import ColorUtils from '../Utils/ColorUtils'
import RouterUtils from '../Utils/RouterUtils'
import ToastUtils from '../Utils/ToastUtils'
import PushUtil from '../Umeng/PushUtil'
import StorageUtils from '../Utils/StorageUtils'
import Constant from "../Constant/Constant"
import HttpUtils from "../Utils/HttpUtils"
import RuleUtils from "../Utils/RuleUtils"

export default class PageLsajList extends React.Component
{
    static navigationOptions = ({navigation}) => ({
        gesturesEnabled: false,//是否支持滑动返回收拾，iOS默认支持，安卓默认关闭
        headerTitle: '综合查询',
        headerStyle: {
            backgroundColor: ColorUtils.blue,
            height: ScreenUtils.statusBarHeight,
        },
        headerRight: (
            <TouchableOpacity onPress={() => DeviceEventEmitter.emit('showAppDeviceDialog', 'param')}>
                <Image resizeMode={Image.resizeMode.stretch} style={{width: 22, height: 22, marginRight: 16}} source={require('../img/filter_head_icon.png')}/>
            </TouchableOpacity>
        ),
        headerTintColor: ColorUtils.white,
        headerTitleStyle: {
            fontSize: ScreenUtils.Font_18,
            color: ColorUtils.white,
            fontWeight: 'normal',
            flex: 1,
            alignSelf: 'center',
            textAlign: 'center',
        }
    });

    constructor(props)
    {
        super(props);
        this.state = {
            timeSolt: '1',
            searchText: '',
            searchCases: [],
            isShowCancelDelete: false,
            pageIndexNeed: 1,
            onRefreshingNeed: true,
            onLoadMoreNeed: false,
            loadMoreCountNeed: 0,
            dataSourceNeed: [],
            isNoDataNeed: false,
        };
    }

    componentDidMount()
    {
        RouterUtils.pushRouter('PageLsajList', this.props.navigation.state.key);
        var that = this;
        this.listener1 = DeviceEventEmitter.addListener('showAppDeviceDialog', function (event)
        {
            if (that.SimpleItemsDialog == null)
            {
                console.log('null')
            } else
            {
                that.SimpleItemsDialog.show()
            }
        });
        this.getNeedList();//获取待处理列表
    }

    componentWillUnmount()
    {
        this.listener1.remove();
        RouterUtils.popRouter('PageLsajList', this.props.navigation.state.key);
    }

    getNeedList()
    {
        try
        {
            var that = this;
            var userName = '';
            var caseNo = '';
            if (RuleUtils.checkAllNumber(that.state.searchText))
            {
                caseNo = that.state.searchText;
                userName = '';
            }
            else
            {
                caseNo = '';
                userName = that.state.searchText;
            }
            StorageUtils.get('session').then((session) =>
            {
                if (session != '' && session != null)
                {
                    HttpUtils.getJson(Constant.searchCase + '?current=' + that.state.pageIndexNeed + '&size=20&caseNo=' + caseNo + '&userName=' + userName + '&timeSlot=' + that.state.timeSolt, session, function (resultcode, data)
                    {
                        if (that.state.pageIndexNeed == 1)
                        {
                            that.setState({
                                onRefreshingNeed: false,
                                onLoadMoreNeed: data.records.length > 0,
                                dataSourceNeed: data.records,
                                loadMoreCountNeed: data.records.length,
                                isNoDataNeed: data.records.length == 0
                            });
                        } else
                        {
                            that.setState({
                                onRefreshingNeed: false,
                                onLoadMoreNeed: data.records.length > 0,
                                dataSourceNeed: that.state.dataSourceNeed.concat(data.records),
                                loadMoreCountNeed: data.records.length,
                                isNoDataNeed: false
                            });
                        }
                    }, function (resultcode, reason)
                    {
                        ToastUtils.toastShortBottom('错误码:' + resultcode + ',错误原因:' + reason);
                    });
                }
            });
        }
        catch (error)
        {
            ToastUtils.toastShortBottom(error);
        }
    }

    jumpDetail(status, id, processInstanceId)
    {
        this.props.navigation.navigate('PageLsajDetail', {'title': '案件详情', 'status': status, 'id': id, 'processInstanceId': processInstanceId});
    }

    searchChange(text)
    {
        if (text.length > 0)
        {
            this.setState({
                isShowCancelDelete: true,
                searchText: text
            })
        } else
        {
            this.setState({
                isShowCancelDelete: false,
                searchText: text
            })
            this.onRefreshNeed();
        }
    }

    searchEnd()
    {
        this.onRefreshNeed();
    }

    cancelSearch()
    {
        this.setState({
            searchText: '',
            isShowCancelDelete: false
        }, () =>
        {
            this.onRefreshNeed();
        })

    }

    renderFooterNeed()
    {
        if (this.state.isNoDataNeed)
        {
            return (
                <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
                    <Image resizeMode={Image.resizeMode.stretch} style={{marginTop: 80, width: 152, height: 120}} source={require('../img/list_nodata.png')}/>
                    <Text style={{fontSize: ScreenUtils.Font_14, color: '#7EA0BF', fontWeight: 'bold', marginTop: 8}}>暂无数据</Text>
                </View>
            );
        }
        if (this.state.loadMoreCountNeed < 20)
        {
            this.state.onLoadMoreNeed = false;
            return null;
        }
        else
        {
            return (
                <View style={{paddingBottom: 2, flexDirection: 'row', justifyContent: 'center', alignItems: 'center'}}>
                    <ActivityIndicator style={{width: 25, height: 25,}} color='#264A70'/>
                    <Text style={{marginLeft: 4, fontSize: ScreenUtils.Font_10}}>执行中...</Text>
                </View>
            );
        }
    }

    onRefreshNeed()
    {
        console.log('pull refresh Need..')
        this.state.pageIndexNeed = 1;
        this.getNeedList();
    }

    onLoadMoreNeed()
    {
        console.log('pull load Log..')
        if (!this.state.onLoadMoreNeed) return null;
        this.state.pageIndexNeed = this.state.pageIndexNeed + 1;
        this.getNeedList();
    }

    renderNeedMsgItem({item})
    {
        return (
            <TouchableOpacity key={item.id} activeOpacity={0.8} onPress={() => this.jumpDetail('未上报', item.id, item.processInstanceId)} style={{paddingTop: 16, paddingLeft: 16, paddingRight: 16}}>
                <View style={{flexDirection: 'row'}}>
                    <View style={{height: '100%', backgroundColor: ColorUtils.blue, width: 3}}/>
                    <View style={{marginLeft: 4, flex: 1, flexDirection: 'column', justifyContent: 'center', marginLeft: 8}}>
                        <View style={{flexDirection: 'row', alignItems: 'center'}}>
                            <Text style={{fontSize: ScreenUtils.Font_14, color: ColorUtils.light_gray}}>案件编号:</Text>
                            <Text style={{marginLeft: 8, fontSize: ScreenUtils.Font_14, color: ColorUtils.black}}>{item.caseNo == "" ? '无' : item.caseNo}</Text>
                        </View>
                        <View style={{marginTop: 8, flexDirection: 'row', alignItems: 'center'}}>
                            <Text style={{fontSize: ScreenUtils.Font_14, color: ColorUtils.light_gray}}>案件类型:</Text>
                            <Text style={{marginLeft: 8, fontSize: ScreenUtils.Font_14, color: ColorUtils.black}}>{item.categoryName}</Text>
                        </View>
                        <View style={{marginTop: 8, flexDirection: 'row', alignItems: 'center'}}>
                            <Text style={{fontSize: ScreenUtils.Font_14, color: ColorUtils.light_gray}}>案件大类:</Text>
                            <Text style={{marginLeft: 8, fontSize: ScreenUtils.Font_14, color: ColorUtils.black}}>{item.categoryOneName}</Text>
                        </View>
                        <View style={{marginTop: 8, flexDirection: 'row', alignItems: 'center'}}>
                            <Text style={{fontSize: ScreenUtils.Font_14, color: ColorUtils.light_gray}}>案件小类:</Text>
                            <Text style={{marginLeft: 8, fontSize: ScreenUtils.Font_14, color: ColorUtils.black}}>{item.categoryTwoName}</Text>
                        </View>
                    </View>
                    <View style={{height: 26, justifyContent: 'center', padding: 6, borderRadius: 4, backgroundColor: '#FFD1D5'}}>
                        <Text style={{color: '#FF192F', fontSize: ScreenUtils.Font_10}}>
                            {RuleUtils.converState(item.state)}
                        </Text>
                    </View>
                </View>
                <View style={{marginTop: 16, height: 1, borderColor: ColorUtils.line, borderBottomWidth: 1}}/>
            </TouchableOpacity>
        );
    }

    render()
    {
        return (
            <View style={styles.container}>
                <View style={{margin: 32, marginTop: 16, marginBottom: 8, paddingLeft: 16, paddingRight: 16, backgroundColor: '#DDDDDD', borderRadius: 32, flexDirection: 'row', alignItems: 'center'}}>
                    <Image resizeMode={Image.resizeMode.stretch} source={require('../img/search_icon.png')} style={{width: 20, height: 20}}/>
                    <TextInput value={this.state.searchText} underlineColorAndroid='transparent' keyboardType='numeric' maxLength={30} placeholder='请输入搜索单号或人员姓名' onChangeText={(text) => this.searchChange(text)} onSubmitEditing={() => this.searchEnd()}
                               multiline={false} style={{marginLeft: 8, fontSize: ScreenUtils.Font_14, flex: 1, height: 40, color: ColorUtils.black}}/>
                    <TouchableOpacity activeOpacity={0.8} onPress={() => this.cancelSearch()}>
                        <Image resizeMode={Image.resizeMode.stretch} source={require('../img/cancel_search.png')} style={{width: 22, height: 22, display: this.state.isShowCancelDelete ? 'flex' : 'none',}}/>
                    </TouchableOpacity>
                </View>
                <AnimatedFlatList
                    data={this.state.dataSourceNeed}
                    keyExtractor={item => item.id}
                    renderItem={this.renderNeedMsgItem.bind(this)}
                    ListFooterComponent={this.renderFooterNeed.bind(this)}
                    refreshing={this.state.onRefreshingNeed}
                    onRefresh={this.onRefreshNeed.bind(this)}
                    onEndReached={this.onLoadMoreNeed.bind(this)}
                    onEndReachedThreshold={1}
                />
                <SimpleItemsBottom
                    items={[{value: '本周'}, {value: '本月'}, {value: '本年'}]}
                    itemKey='value'
                    ref={ref => this.SimpleItemsDialog = ref}
                    onPress={(which) =>
                    {
                        if (which == '0')
                        {
                            this.state.timeSolt = '1';
                            this.onRefreshNeed();
                        } else if (which == '1')
                        {
                            this.state.timeSolt = '2';
                            this.onRefreshNeed();
                        } else
                        {
                            this.state.timeSolt = '3';
                            this.onRefreshNeed();
                        }
                    }}/>
            </View>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: ColorUtils.white,
    },
});
